﻿//VARIABLES GLOBALES
var $msgPopup;

//POPUP PARA MOSTRAR INFORMACION
function showInfo(msg, funcClose) {
    if ($msgPopup == null) {
        var buttons = {};
        buttons['Cerrar'] = function () { $(this).dialog('close'); };

        $msgPopup = $('<div id="divInfoPopup" title="Info" style="display: none;"></div>');
        $msgPopup.dialog({
            height: 'auto',
            width: 410,
            autoOpen: false,
            modal: true,
            buttons: buttons,
            close: funcClose,
            zIndex: 2000
        });
    }

    $msgPopup.html($("<p></p>").html(msg).html()).dialog('open');
    return false;
}

//SE MUESTRA ELL POPUP DE CARGA
function loadingDivPopUp() {
    $divLoading.dialog('open');
}
//SE ESCONDE EL POPUP DE CARGA
function loadingDivPopUpHide() {
    $divLoading.dialog('close');
}

//DIBUJA EL HTML DENTRO DEL POPUP
function putContentHtmlDivPopup($divModal, html) {
    $divModal.find("#content").html(html);
}

//ABRE EL POPUP
function openModal(url, $divModal, funcSuccess, errorMsg) {
    var closeEvent = $divModal.dialog("option", "close");

    if (typeof closeEvent !== 'function') {
        $divModal.dialog("option", "close", function () {
            //removeToolTips();
            putContentHtmlDivPopup($divModal, "");
        });
    }

    $divModal.dialog('open');
    loadingDivPopUp();

    if (errorMsg === undefined) {
        errorMsg = errorMessage;
    }

    $.ajax({
        type: "get",
        url: url,
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            $divModal.dialog('close');
            loadingDivPopUpHide();
            showInfo("[openModal]: " + errorMsg + "\n" + XMLHttpRequest.responseText);
        },
        success: funcSuccess
    });
}

//SUBMIT DEL FORMULARIO
function submitForm(idForm, $divModal, funcSuccess, errorMsg) {
    var $form = $(idForm);
    if (isValidForm(idForm)) {
        if (errorMsg === undefined) {
            errorMsg = errorMessage;
        }

        var formData = serializeFormDataToArray($form);
        var url = $form.attr("action");
        loadingDivPopUp();

        if ($form.attr('enctype') == "multipart/form-data") {
            $form.submit(function (e) {
                var formData = new FormData(this);
                $.ajax({
                    type: 'POST',
                    dataType: "json",
                    url: url,
                    data: formData,
                    mimeType: "multipart/form-data",
                    contentType: false,
                    cache: false,
                    processData: false,
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        loadingDivPopUpHide();
                        showInfo("[submitForm]: " + errorMsg + "\n" + XMLHttpRequest.responseText);
                    },
                    success: funcSuccess
                });
                e.preventDefault(); //Prevent Default action. 
            })
            $form.submit();
        }
        else {
            $.ajax({
                type: "post",
                dataType: "json",
                url: url,
                data: formData,
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    loadingDivPopUpHide();
                    showInfo("[submitForm]: " + errorMsg + "\n" + XMLHttpRequest.responseText);
                },
                success: funcSuccess
            });
        }
    }
}

//ACTIVA LAS VALIDACIONES
function bindClientValidation(idForm) {
    var $form = $(idForm);
    $form.removeData("validator");
    $form.removeData("unobtrusiveValidation");
    $.validator.unobtrusive.parse(idForm);

    var validator = $form.data('validator');

    var oldOnErrorMethod = validator.settings.errorPlacement;

    // Sobreescribir comportamiento de OnError() de jquery.validate.unobstrusive()
    validator.settings.errorPlacement = function (error, inputElement) {
        oldOnErrorMethod(error, inputElement);

        /**** Added code to display the error message in a qTip tooltip ****/
        // Set positioning based on the elements position in the form
        var $elem = $(inputElement); //,
        //corners = ['left center', 'right center'],
        //flipIt = elem.parents('span.right').length > 0;

        // Check we have a valid error message
        if (!error.is(':empty')) {
            // Apply the tooltip only if it isn't valid

            var elementsWithTooltip = $elem.filter(':not(.valid)');
            removeTooltipsOfElements(elementsWithTooltip);
            loadErrorToolTips(elementsWithTooltip, error.text());

            // If we have a tooltip on this element already, just update its content
            //.qtip('option', 'content.text', error);
        }

        // If the error is empty, remove the qTip
        else { $elem.qtip('destroy'); }
    };

    // Run this function for all validation error messages
    $form.find('.field-validation-error').each(function () {
        // Get the name of the element the error message is intended for
        // Note: ASP.NET MVC replaces the '[', ']', and '.' characters with an
        // underscore but the data-valmsg-for value will have the original characters
        var inputElem = '#' + $(this).attr('data-valmsg-for').replace('.', '_').replace('[', '_').replace(']', '_');

        // Hide the default validation error
        $(this).hide();
        // Show the validation error using qTip

        var elementsWithTooltip = $form.find(inputElem).filter(':not(.valid)');
        removeTooltipsOfElements(elementsWithTooltip);
        loadErrorToolTips(elementsWithTooltip, $(this).text());
    });
}

/// Agrega tooltips (qTip) a los elementos, para mostrar mensajes de error
///
function loadErrorToolTips(elements, errorText) {
    elements.qtip({
        override: true,
        content: { text: errorText },
        position: {
            my: 'left center',
            at: 'right center',
            viewport: $(window)
        },
        show: {
            ready: true,
            effect: function (offset) {
                $(this).show().animate({ "opacity": "0" }, 0).animate({ "margin-left": "0", "opacity": "1" }, 200);
            }
        },
        hide: {
            effect: function (offset) {
                $(this).animate({ "margin-left": "-20px", "opacity": "0" }, { duration: 200, complete: function () { $(this).hide(); } });
            },
            fixed: true // Helps to prevent the tooltip from hiding ocassionally when tracking!
        },
        style: {
            classes: 'qtip-red qtip-shadow qtip-rounded'  // Make it red... the classic error colour!
        }
    });
}

function removeTooltipsOfElements(elements) {
    elements.each(function () {
        if ($(this).attr('data-hasqtip')) {
            var qtipId = $(this).attr('aria-describedby');
            $('#' + qtipId).remove();
        }
    });
}

//VALIDA EL FORMULARIO
function isValidForm(idForm) {
    var $form = $(idForm);
    if ($form.is('form')) {
        $form.find('input[waterMark]').each(function () {
            var id = $(this).attr('id');
            $.watermark.hide(idForm + " #" + id);
        });
        var isValid = $form.valid();
        $form.find('input[waterMark]').each(function () {
            var id = $(this).attr('id');
            $.watermark.show(idForm + " #" + id);
        });
        return isValid;
    }
    return false;
}

function loadWaterMarks(idContainer) {
    $.watermark.options.className = 'waterMark';
    $.watermark.options.useNative = false;  // true: usa placeholder (html5), false: usa class watermark (IE y html4)
    $.watermark.options.hideBeforeUnload = true;

    var $container;
    if (idContainer === undefined)
        $container = $('input[waterMark]');
    else
        $container = $(idContainer).find('input[waterMark]');

    $container.each(function () {
        var wmValue = $(this).attr('waterMark');
        $(this).watermark(wmValue);
    });
}


//LEE LA URL CARGADA, USADA PARA IMAGENES
function readURL(input, holder) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();
        reader.onload = function (e) {
            $('#' + holder).attr('src', e.target.result);
        }
        reader.readAsDataURL(input.files[0]);
    }
}

function serializeFormDataToArray($form) {
    var disabledElements = $form.find('textarea:disabled,select:disabled,input:disabled').removeAttr('disabled');

    var formData = $form.serializeArray();

    disabledElements.attr('disabled', 'disabled');

    return formData;
}